<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="24">
        <el-form class="login_form" :model="loginForm" :rules="rules" ref="loginForms">
          <h1>Hello</h1>
          <h2>welcome to the Palworld</h2>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" v-model="userSrote.account" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" :prefix-icon="Lock" show-password v-model="userSrote.password" />
            <!-- <el-input type="password" :prefix-icon="Lock" /> -->
          </el-form-item>
          <el-form-item>
            <el-button class="login_btn" type="primary" @click="login" :loading="loading"
              :disabled="loading">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script setup lang="ts">
import { useUserSrote } from '@/stores/modules/user'
import { reactive, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'

const route = useRoute()
const router = useRouter()

const userSrote = useUserSrote()

// 登录按钮loading
let loading = ref(false)

// 表单数据
// const loginForm = new FormData();
// loginForm.append('account', userSrote.account);
// loginForm.append('password', userSrote.password);
// let loginForm = {
//   account: userSrote.account,
//   password: userSrote.password
// }
// let loginForm = Object.assign({userSrote.account},{userSrote.password})

let loginForm = computed(() => ({
  account: userSrote.account,
  password: userSrote.password // 假设这是另一个状态或计算结果
}));

// 表单验证
const rules = reactive({
  // account: [
  //   { required: true, message: '用户名不能为空', trigger: 'change' },
  //   { min: 4, max: 16, message: '用户名必须为4-16位', trigger: 'change' },
  // ],
  // password: [
  //   { required: true, message: '密码不能为空', trigger: 'change' },
  // ],
})

const loginForms = ref()

// 登录

const login = async () => {

  // 表单验证
  await loginForms.value.validate()
  loading.value = true

  // 登录发起请求
  let loginReturn = await userSrote.userLogin(loginForm.value)
  if(loginReturn.code == 1){

    // 获取用户信息
    await userSrote.getUserInfo()

    ElNotification({
      title: `Hi,${getTime()}好`,
      message: '登录成功',
      type: 'success',
    })
    loading.value = false
    const redirect: any = route.query.redirect
    router.push({ path: redirect || '/' })
  }else{
    ElNotification.error(loginReturn.msg)
    loading.value = false
  }
}
</script>
<style scoped lang="scss"></style>
